package com.bluemobi.www.security.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;

import com.bluemobi.www.constant.Constant;
import com.bluemobi.www.utils.CreateImageCode;
import com.bluemobi.www.utils.SessionUtils;

@Controller
public class SecurityController {


	/**
	 * 执行登出操作
	 */
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(SessionStatus status) {
		status.setComplete();
		SessionUtils.clear();
		return "redirect:/index";
	}

	/**
	 * 首页
	 */
	@RequestMapping(value = {
			"/index", "/"
	})
	public String index() {
		return "login";
	}

	/**
	 * 获取验证码
	 */
	@RequestMapping(value = "/captcha", method = RequestMethod.GET)
	public void validateImages(HttpServletResponse response) throws IOException {
		Random random = new Random();
		CreateImageCode vCode = new CreateImageCode(160,40,4,10,random.nextInt(3)%3 + 1);
		BufferedImage image = vCode.getBuffImg();
		String validateCode = vCode.getCode();
		System.out.println(validateCode);
		SessionUtils.put(Constant.CURRENT_USER_VALIDATE_CODE_KEY, validateCode);
		ImageIO.write(image, "png", response.getOutputStream());
	}

	/**
	 * 未授权
	 */
	@RequestMapping(value = "/error")
	public String unauthorized() {
		return "error";
	}

}
